<template>
  <div class="page container stick-tag" :style="'min-height:' + minHeight + 'px'">
    <div class="sticked-tags">
      <div class="tags-body">
        <div class="row">
          <popover placement="bottom" v-for="tag in stickedTags">
            <div slot="content" class="popover-tag-content" @click="handleTag(tag)">删除</div>
            <span class="tags-item active">{{ tag.tagName }}</span>
          </popover>
          <input ref="inputTag" @blur="enterTag" v-model="newTag.tagName" placeholder="输入标签, 点击空白处确认" class="tags-item input-tag" />
        </div>
      </div>
    </div>
    <div class="unstick-tags">
      <h3 class="tags-title">所有标签</h3>
      <div class="tags-body">
        <div class="row">
          <template v-for="tag in allTags">
            <popover placement="bottom" v-if="inStickedTag(tag) === true">
              <div slot="content" class="popover-tag-content" @click="handleTag(tag)">删除</div>
              <span class="tags-item active">{{ tag.tagName }}</span>
            </popover>
            <span v-else class="tags-item" @click="handleTag(tag, false)">{{ tag.tagName }}</span>
          </template>
        </div>
      </div>
    </div>

    <span class="scrm-default-btn" v-if="newTag.tagName">保存</span>
  </div>
</template>
<script>
  import { mapActions } from 'vuex'
  import Popover from 'vux/src/components/popover'
  import Q from 'q'

  export default {
    directives: {
      focus: {
        // 指令的定义---
        inserted (el, directive, node) {
          // Focus the element
          el.focus()
        }
      }
    },
    beforeMount () {
    },
    components: {
      Popover
    },
    mounted () {
      this.callJsApi('biz.navigation.setTitle', {title: '贴标签'})
      this.custom_id = this.$route.query.id
      this.listener()
      this.trigger(this.$refs['inputTag'], 'click')
      this.initialize()
    },
    methods: {
      trigger (element, eventName) {
        let event
        // IE
        if (document.createEvent) {
          event = document.createEvent('HTMLEvents')
          event.initEvent(eventName, true, true)
        } else {
          event = document.createEventObject()
          event.eventType = eventName
        }

        event.eventName = eventName

        if (document.createEvent) {
          element.dispatchEvent(event)
        } else {
          element.fireEvent('on' + event.eventType, event)
        }
      },
      initialize () {
        this.$vux.loading.show({ text: 'loading' })
        this.tagSign() // 先签名
          .then(this.initAllTags) // 再获取所有标签
          .then(this.initStickedTags) // 再获取已贴标签
          .finally(() => {
            this.$vux.loading.hide()
          })

        const customType = parseInt(this.$route.query.custom_type)
        this.tagObjectCode = customType === 0 ? 'social_customer' : 'normal_customer'
      },
      listener () {
        this.minHeight = window.innerHeight
        window.addEventListener('resize', () => {
          this.minHeight = window.innerHeight
        })
        const inputTag = this.$refs['inputTag']
        inputTag.addEventListener('click', () => {
          inputTag.focus()
        })
      },
      enterTag (el) {
        if (this.newTag.tagName.replace('', '')) {
          this.stickedTags.push(Object.assign({}, this.newTag))
          this.dolinkTag(this.newTag)
          this.newTag = {
            tagId: null,
            tagName: ''
          }
          this.trigger(this.$refs['inputTag'], 'click')
        }
      },
      // 判断标签是否已选
      inStickedTag (tag) {
        let isSticked = false
        this.stickedTags.forEach((stickedTag, index) => {
          if (tag.tagId === stickedTag.tagId) {
            isSticked = true
          }
        })
        return isSticked
      },
      findStickedTagIndex (tag) {
        let tmpIndex = -1
        this.stickedTags.forEach((stickedTag, index) => {
          if (tag.tagId === stickedTag.tagId) {
            tmpIndex = index
          }
        })
        return tmpIndex
      },
      initAllTags () {
        return Q.Promise((resolve, reject) => {
          this.findAllTags().then((response) => {
            if (response.data.errcode === 0) {
              this.allTags = response.data.myTags
            }
            resolve()
          }).catch((err) => {
            resolve({})
            console.log(err)
          })
        })
      },
      initStickedTags () {
        return Q.Promise((resolve, reject) => {
          this.findObjectTags({ businessId: this.custom_id, tagObjectCode: this.tagObjectCode }).then((response) => {
            if (response.data.errcode === 0) {
              this.stickedTags = response.data.list
            }
            resolve()
          }).catch((err) => {
            resolve()
            console.log(err)
          })
        })
      },
      // 贴标签
      dolinkTag (tag) {
        this.$vux.loading.show({text: '保存中...'})
        return Q.Promise((resolve, reject) => {
          // 如果标签不存在，先创建一个新的标签
          if (!tag.tagId) {
            this.createTag(tag).then((data) => {
              tag.tagId = data.tagId
              resolve(tag)
              console.log(data)
            }).catch(() => {
              alert('网络有问题，请联系网管处理');
              this.$vux.loading.hide()
            })
          } else {
            resolve(tag)
          }
        }).then((tag) => {
          return Q.Promise((resolve, reject) => {
            this.linkTag({
              businessId: this.custom_id,
              tagId: tag.tagId,
              tagObjectCode: this.tagObjectCode
            }).then((response) => {
              this.$vux.loading.hide()
              if (response.data.errcode === 0) {
                alert('保存标签成功!')
                tag.tagObjectId = response.data.tagObjectId
                resolve()
              } else {
                alert('网络有问题，请联系网管处理');
                reject(response.data)
              }
            })
          })
        }).catch((error, data) => {
          // 此处预留做dialog处理
          console.log(data)
          console.log(error)
          this.$vux.loading.hide()
        })
      },
      // 创建标签
      createTag (tag) {
        return Q.Promise((resolve, reject) => {
          this.tag(tag).then((response) => {
            if (response.data.errcode === 0) {
              resolve(response.data)
            } else {
              reject({
                errcode: 10001,
                errormsg: '创建标签失败'
              })
            }
          }).catch(() => {
            reject({
              errcode: 10001,
              errormsg: '创建标签失败'
            })
          })
        })
      },
      doUnLinkTag (tag) {
        this.$vux.loading.show({text: '移除标签中...'})
        return Q.Promise((resolve, reject) => {
          this.unlinkTag(tag).then((response) => {
            // const index = this.findStickedTagIndex(tag)
            // this.stickedTags.splice(index, 1)
            this.$vux.loading.hide()
            if (response.data.errcode === 0) {
              alert('移除标签成功')
            } else {
              reject({
                errcode: 10001,
                errormsg: '删除标签失败'
              })
            }
          }).catch(() => {
            alert('删除标签失败')
            reject({
              errcode: 10001,
              errormsg: '删除标签失败'
            })
          })
        })
      },
      // 处理标签点击
      handleTag (tag, removable) {
        const stickedTagIndex = this.findStickedTagIndex(tag)
        if (stickedTagIndex > -1) {
          if (removable !== false) {
            tag.active = false
            tag = Object.assign({}, tag, this.stickedTags[stickedTagIndex])
            this.doUnLinkTag(tag)
            this.stickedTags.splice(stickedTagIndex, 1)
          }
        } else {
          this.stickedTags.push(tag)
          tag.active = true
          this.dolinkTag(tag)
        }
      },
      ...mapActions({
        'linkTag': 'linkTag',
        'unlinkTag': 'unlinkTag',
        'tag': 'tag',
        'findAllTags': 'findAllTags',
        'queryObjectsByTag': 'queryObjectsByTag',
        'findObjectTags': 'findObjectTags',
        'tagSign': 'tagSign'
      })
    },
    data () {
      return {
        custom_id: '',
        minHeight: '',
        newTag: {
          tagId: null,
          tagName: ''
        },
        tagObjectCode: 'normal_customer',
        stickedTags: [
          // {
          //   tagId: 1,
          //   tagName: '美丽'
          // }
        ], // 已贴标签
        allTags: [
          // {
          //   tagId: 1,
          //   tagName: '美丽'
          // },
          // {
          //   tagId: 2,
          //   tagName: '帅气'
          // }
        ] // 未贴标签
      }
    }
  }
</script>
<style lang="less">
  @import "../less/base";
  .stick-tag {
    background-color: #fbfbfb;
    overflow-x: hidden;
    overflow-y: auto;

    .sticked-tags {
      padding: 10px 10px;
      background-color: white;
      min-height: 20px;
    }

    .tags-title {
      padding: 10px 0;
      color: #a9a7a7;
      font-size: 16px;
    }

    .tags-body {
      overflow: hidden;

      .row {
        overflow: hidden;
        margin-top: -10px;
      }
    }

    .tags-item {
      border: 1px solid #cccaca;
      padding: 4px 10px;
      font-size: 14px;
      border-radius: 10px;
      min-width: 20px;
      margin-right: 16px;
      margin-top: 10px;
      float: left;


      &.active {
        color: #35ADFF;
        border: 1px solid #35ADFF;
      }
    }

    .input-tag {
      outline: none;
      border: none;
      height: 24px;
      width: 164px;
    }

    .unstick-tags {
      padding: 0 10px;
    }

    .popover-tag-content {
      font-size: 12px;
      padding: 2px 14px;
    }

    .scrm-default-btn  {
      margin-top: 30px;
      width: 60px;
    }
  }
</style>
